package com.hethongviet.doorcontroller.page;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hethongviet.preventer.config.InitSettings;
import com.hethongviet.preventingmachine.AppMain;
import com.hethongviet.preventingmachine.Config;
import com.hethongviet.preventingmachine.Constants;
import com.hethongviet.preventingmachine.R;
import com.hethongviet.preventingmachine.Utils;
import com.hethongviet.preventingmachine.helps.OnSMSMessageFailListener;
import com.hethongviet.preventingmachine.helps.OnSMSMessageListener;
import com.hethongviet.preventingmachine.helps.SMSHelper;
import com.hethongviet.preventingmachine.helps.SmsReceiverDoor;
import com.hethongviet.preventingmachine.helps.TabMenu;
import com.hethongviet.preventingmachine.helps.db.ClientSQLite;
import com.hethongviet.preventingmachine.helps.db.RelaySQLite;
import com.hethongviet.preventingmachine.helps.db.SensorSQLite;
import com.hethongviet.preventingmachine.models.Client;
import com.hethongviet.preventingmachine.models.Relay;
import com.hethongviet.preventingmachine.models.SMS;
import com.hethongviet.preventingmachine.models.Tab;
import com.hethongviet.preventingmachine.models.Transaction;

public class PageMainActivity extends Activity implements OnSMSMessageListener,
		OnSMSMessageFailListener
{
	private final static int TAB_MAIN = 0;
	private final static int TAB_SCROLL = TAB_MAIN + 1;
	private final static int TAB_OTHER = TAB_SCROLL + 1;
	private final static int TOTAL_TABS = TAB_OTHER + 1;

	private final static int INDEX_RELAY_SCROLL_UP = 0;
	private final static int INDEX_RELAY_SCROLL_DOWN = 1;
	private final static int INDEX_RELAY_SCROLL_STOP = 2;

	private final static int INDEX_RELAY_MAIN_OPEN = 4;
	private final static int INDEX_RELAY_MAIN_CLOSE = 3;
	private final static int INDEX_RELAY_MAIN_STOP = 5;

	private final static int INDEX_RELAY_OTHER1 = 6;
	private final static int INDEX_RELAY_OTHER2 = 7;

	private Client _Client = null;

	private TextView _TextViewWaitAdmin = null;

	private List<Relay> _RelayList = null;

	private LinearLayout _LayoutDoorControl = null;

	private ClientSQLite _ClientSQLite = null;
	private RelaySQLite _RelaySQLite = null;

	private Button _ButtonDoorScrollUp = null;
	private Button _ButtonDoorScrollDown = null;
	private Button _ButtonDoorScrollStop = null;
	private Button _ButtonDoorScrollLock = null;

	private Button _ButtonDoorMainOpen = null;
	private Button _ButtonDoorMainClose = null;
	private Button _ButtonDoorMainStop = null;
	private Button _ButtonDoorMainLock = null;

	private Button _ButtonDoorOther1 = null;
	private Button _ButtonDoorOther2 = null;

	private Button _ButtonTabDoorMain = null;
	private Button _ButtonTabDoorScroll = null;
	private Button _ButtonTabDoorOther = null;

	private ScrollView _ScrollViewTabDoorMain = null;
	private ScrollView _ScrollViewTabDoorScroll = null;
	private ScrollView _ScrollViewTabDoorOther = null;

	private boolean _isControlledDoor = false;

	private boolean _isLockDoorMain = false;
	private boolean _isLockDoorScroll = false;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		Utils.prepareWindow(this);

		setContentView(R.layout.page_user);

		_ButtonDoorScrollDown = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_scroll_down);
		_ButtonDoorScrollLock = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_scroll_lock);
		_ButtonDoorScrollStop = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_scroll_stop);
		_ButtonDoorScrollUp = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_scroll_up);

		_ButtonDoorMainClose = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_main_close);
		_ButtonDoorMainLock = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_main_lock);
		_ButtonDoorMainOpen = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_main_open);
		_ButtonDoorMainStop = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_main_stop);

		_ButtonDoorOther1 = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_other_1);
		_ButtonDoorOther2 = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_other_2);

		_ButtonTabDoorMain = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_tab_door_main);
		_ButtonTabDoorScroll = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_tab_door_scroll);
		_ButtonTabDoorOther = (Button) findViewById(com.hethongviet.doorcontroller.R.id.button_tab_other);

		_ScrollViewTabDoorMain = (ScrollView) findViewById(com.hethongviet.doorcontroller.R.id.layout_tab_door_main);
		_ScrollViewTabDoorOther = (ScrollView) findViewById(com.hethongviet.doorcontroller.R.id.layout_tab_door_other);
		_ScrollViewTabDoorScroll = (ScrollView) findViewById(com.hethongviet.doorcontroller.R.id.layout_tab_door_scroll);

		_TextViewWaitAdmin = (TextView) findViewById(com.hethongviet.doorcontroller.R.id.text_wait_admin);
		_LayoutDoorControl = (LinearLayout) findViewById(com.hethongviet.doorcontroller.R.id.layout_main);

		initDB();

		initTab();

		if (Config.IS_DEBUG_NOT_WAIT_ADMIN)
		{
			_Client = new Client();
			_Client.setControlled(true);
			_Client.setDeviceNumber(Constants.DEVICE_NUMBER_DEFAULT);

			_ClientSQLite.insert(_Client);
		}

		List<Client> clients = null;

		try
		{
			clients = _ClientSQLite.getAll();
		} catch (Exception e)
		{
			e.printStackTrace();
		}

		if (clients == null || clients.size() == 0)
		{
			_RelayList = null;
			_Client = new Client();
		}
		else
		{
			_Client = clients.get(0);

			SMSHelper.setDeviceNumber(_Client.getDeviceNumber());
			SMSHelper.setMessageId(0);

			try
			{
				_RelayList = _RelaySQLite.getAll();
			} catch (Exception e)
			{
				e.printStackTrace();
			}

			_TextViewWaitAdmin.setVisibility(View.GONE);

			_LayoutDoorControl.setVisibility(View.VISIBLE);

		}

		proccessButton();

	}

	private void proccessButton()
	{

		_ButtonDoorScrollDown.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				controlDoor(INDEX_RELAY_SCROLL_DOWN);
			}
		});

		_ButtonDoorScrollLock.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				if (InitSettings.IS_WAIT_FOR_DONE_CONTROL)
				{
					if (_isControlledDoor)
						return;

					_isControlledDoor = true;

					Utils.showProgress(PageMainActivity.this);
				}

				_isLockDoorScroll = !_isLockDoorScroll;

				SMSHelper.proccesslock(_isLockDoorScroll ? SMSHelper.CODE_LOCK_2
						: SMSHelper.CODE_UNLOCK_2, R.string.message_fail_lock);
				debugSendSMS(SMSHelper.DEBUG_SMS_CODE_LOCK_2);

			}
		});

		_ButtonDoorScrollStop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				controlDoor(INDEX_RELAY_SCROLL_STOP);
			}
		});

		_ButtonDoorScrollUp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				controlDoor(INDEX_RELAY_SCROLL_UP);
			}
		});

		_ButtonDoorMainClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				controlDoor(INDEX_RELAY_MAIN_CLOSE);
			}
		});

		_ButtonDoorMainOpen.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				controlDoor(INDEX_RELAY_MAIN_OPEN);
			}
		});

		_ButtonDoorMainStop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				controlDoor(INDEX_RELAY_MAIN_STOP);
			}
		});

		_ButtonDoorMainLock.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				if (InitSettings.IS_WAIT_FOR_DONE_CONTROL)
				{
					if (_isControlledDoor)
						return;

					_isControlledDoor = true;

					Utils.showProgress(PageMainActivity.this);
				}

				_isLockDoorMain = !_isLockDoorMain;

				SMSHelper.proccesslock(_isLockDoorMain ? SMSHelper.CODE_LOCK_1
						: SMSHelper.CODE_UNLOCK_1, R.string.message_fail_lock);
				debugSendSMS(SMSHelper.DEBUG_SMS_CODE_LOCK_1);

			}
		});

		_ButtonDoorOther1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				controlDoor(INDEX_RELAY_OTHER1);
			}
		});

		_ButtonDoorOther2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				controlDoor(INDEX_RELAY_OTHER2);
			}
		});

	}

	private void controlDoor(int relayIndex)
	{
		if (InitSettings.IS_WAIT_FOR_DONE_CONTROL)
		{
			if (_isControlledDoor)
				return;

			_isControlledDoor = true;

			Utils.showProgress(PageMainActivity.this);
		}

		/* SMS turn relay */
		SMSHelper.controlRelay(Constants.MAX_RELAYS, relayIndex, true, R.string.message_fail_control_relay, null);
		debugSendSMS(SMSHelper.DEBUG_SMS_CONTROL_DEVICE);

	}

	private void initTab()
	{
		/* Process for tab menu */
		Tab[] tabs = new Tab[TOTAL_TABS];

		tabs[TAB_MAIN] = new Tab();
		tabs[TAB_MAIN].setButton(_ButtonTabDoorMain);
		tabs[TAB_MAIN].setViewContain(_ScrollViewTabDoorMain);

		tabs[TAB_SCROLL] = new Tab();
		tabs[TAB_SCROLL].setButton(_ButtonTabDoorScroll);
		tabs[TAB_SCROLL].setViewContain(_ScrollViewTabDoorScroll);

		tabs[TAB_OTHER] = new Tab();
		tabs[TAB_OTHER].setButton(_ButtonTabDoorOther);
		tabs[TAB_OTHER].setViewContain(_ScrollViewTabDoorOther);

		new TabMenu(tabs, R.drawable.button_tab2,
				R.drawable.button_tab2_highlight);
	}

	private void initDB()
	{
		SensorSQLite sensorSQLite = new SensorSQLite(this,
				AppMain.getInstance().getDBName());
		sensorSQLite.open();
		sensorSQLite.close();

		_RelaySQLite = new RelaySQLite(this, AppMain.getInstance().getDBName());
		_ClientSQLite = new ClientSQLite(this,
				AppMain.getInstance().getDBName());

	}

	@Override
	protected void onResume()
	{

		SmsReceiverDoor.setOnSMSMessageListener(this);
		SMSHelper.setActivity(this);
		SMSHelper.setMessageId(0);

		super.onResume();
	}

	@Override
	public void onSMSMessageIncoming(SMS sms)
	{

		Utils.debug("Message receive = " + sms.getMessage());
		String message = Utils.prepareMessage(sms.getMessage());

		if (Utils.isStringNull(message))
		{
			Utils.debug("ERROR----- wrong message! NULL");
			return;
		}

		if (message.contains(SMSHelper.CODE_SYNCHRONIZE_NUMBERS_CONTROL))
		{

			Utils.debug("CODE_SYNCHRONIZE_NUMBERS_CONTROL");

			String messageContent = SMSHelper.getContent(message, SMSHelper.CODE_SYNCHRONIZE_NUMBERS_CONTROL.length());

			if (Utils.isStringNull(messageContent))
			{
				Utils.debug("ERROR----- wrong messageContent! NULL");
				return;
			}

			String[] strings = messageContent.split("["
					+ SMSHelper.CODE_SEPARATE + "]");

			if (strings == null || strings.length <= 2)
			{
				Utils.debug("ERROR----- wrong messageContent.split! NULL");
				return;
			}

			String number = strings[0];
			int totalRelays = strings.length - 1;

			runOnUiThread(new Runnable() {

				@Override
				public void run()
				{
					Utils.toast(PageMainActivity.this, R.string.message_receive_from_admin);
				}
			});

			_Client.setControlled(true);
			_Client.setAlarmed(false);
			_Client.setDeviceNumber(number);

			SMSHelper.setDeviceNumber(number);
			_ClientSQLite.insert(_Client);

			_RelaySQLite.deleteAll();
			_RelayList = new ArrayList<Relay>();
			for (int i = 0; i < totalRelays; i++)
			{
				Relay relay = new Relay(strings[i + 1], i + 2, false);
				_RelayList.add(relay);
				_RelaySQLite.insert(relay);
			}

			_RelayList = _RelaySQLite.getAll();

			SMSHelper.synchronizeOfUser(sms.getRecipient(), SMSHelper.CODE_SYNCHRONIZE_NUMBERS_CONTROL, message.substring(message.length() - 3, message.length()));

			runOnUiThread(new Runnable() {
				
				@Override
				public void run()
				{
					_LayoutDoorControl.setVisibility(View.VISIBLE);
					_TextViewWaitAdmin.setVisibility(View.GONE);
				}
			});
		}
		else
		{
			Utils.debug("Message receive valid = " + message);
			Transaction transaction = SMSHelper.solve(message);

			if (transaction != null)
			{
				String codeSMS = transaction.getCodeSend();
				Utils.debug("codeSMS = " + codeSMS);

				if (codeSMS == null || codeSMS.equals(""))
				{
					Utils.debug("ERROR----- wrong message! NULL");
					return;
				}

				String contentSMS = transaction.getMessageReceive();
				Utils.debug("contentSMS = " + contentSMS);

				if (codeSMS.equals(SMSHelper.CODE_CONTROL_DEVICE))
				{
					Utils.debug("CODE_CONTROL_DEVICE contentSMS = "
							+ contentSMS);

					Utils.hideProgressDialog();

					_isControlledDoor = false;
				}
			}
		}
	}

	private void debugSendSMS(final String message)
	{

		final SMS sms = new SMS();
		sms.setRecipient(SMSHelper.getDeviceNumber());
		sms.setMessage(message);

		if (Config.IS_DEBUG_SMS_RECEIVE)
		{
			new Thread(new Runnable() {

				@Override
				public void run()
				{
					try
					{
						Thread.sleep(Constants.TIME_DEBUG_SEND_SMS);
					} catch (Exception e)
					{
						e.printStackTrace();
					}
					PageMainActivity.this.runOnUiThread(new Runnable() {

						@Override
						public void run()
						{
							onSMSMessageIncoming(sms);
						}
					});
				}
			}).start();

		}
	}

	@Override
	public void onSMSMessageFail(final Transaction transaction,
			final int messageFailId)
	{
		runOnUiThread(new Runnable() {

			@Override
			public void run()
			{
				if (messageFailId > 0)
					Utils.toast(PageMainActivity.this, messageFailId);

				switch (messageFailId)
				{

					default:
						break;
				}
			}
		});

	}
}
